local skynet = require "skynet"
require "skynet.manager"
local Socket = require "skynet.socket"
local ServiceName = require "enum.ServiceName"
local Service = require "core.Service"

local M = {}

local gatecount
---@type ApiGate[]
local slaves = {}
local adminHost

local balance = 1
function M.start(conf)
    gatecount = conf.gatecount or 8

    adminHost = conf.admin_host
    local master = skynet.self()
    for i = 1, gatecount do
        ---@type ApiGate
        local s = Service:new(skynet.new_hotservice("service.ApiGate"))
        s:start({
            master = master,
            protocol = conf.protocol
        })
        table.insert(slaves, s)
    end

    local server = Socket.listen(conf.host, conf.port)
    Socket.start(server, function(id, addr)
        -- 只接收来自于 admin 的请求
        if addr ~= adminHost then
            LLOG("api_master", "addr hack, addr: " .. addr)
            Socket.close(id)
            return
        end

        local s = slaves[balance]
        balance = balance + 1
        if balance > gatecount then
            balance = 1
        end

        s.handle(id)
    end)
end

function M.init()
    skynet.dispatch_lua(M)
    skynet.register(ServiceName.API_MASTER)
end

return M
